/* tripl/error.c 
 * 
 * This file is part of tripl. 
 * 
 * tripl is free software: you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation, either version 3 of the License, or 
 * (at your option) any later version. 
 * 
 * tripl is distributed in the hope that it will be useful, 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
 * GNU General Public License for more details. 
 * 
 * You should have received a copy of the GNU General Public License 
 * along with tripl. If not, see <https://www.gnu.org/licenses/>
 */ 




#include <tripl/tripl.h>
#include <tripl/limits.h>

#include <string.h>


extern char *line_eof;
static int ge_dump_line(int ln, char *buffer);

/* yeah, you know, the color_printk() in that book :-) */
#define color_error(mode, fg, msg, ...) 			\
	ansi_csi_st(stderr, mode, fg, BG_BLACK); 		\
	fprintf(stderr, msg, ##__VA_ARGS__); 			\
	ansi_csi_ed(stderr); 					\


int generic_error(char *msg, char *line, int lno) {
	char *buffer = strndup(line, line_eof - line + 1);

	color_error(MODE_HIGHLIGHT, FG_WHITE, "tripl: %s:%d: ", fname, lno);
	color_error(MODE_HIGHLIGHT, FG_RED, "error: ");

	fprintf(stderr, "%s\n", msg);

	ge_dump_line(lno, buffer);

	free(buffer);

	return 1;
}


static int ge_dump_line(int ln, char *buffer) {
	while (*buffer && *buffer++ == '\n') 
		;

	fprintf(stderr, "%5d | %s\n", ln, buffer);
	
	return 0;
}


